package emon.eline.manage.media.service;

import emon.eline.manage.media.dao.MediaFileRepository;
import emon.eline.manage.media.dto.QueryMediaFileRequest;
import emon.eline.manage.media.entity.MediaFile;
import emon.eline.model.CommonCode;
import emon.eline.model.QueryResponseResult;
import emon.eline.model.QueryResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MediaFileService {
    @Autowired
    private MediaFileRepository mediaFileRepository;

    public QueryResponseResult findList(int page, int size, QueryMediaFileRequest queryMediaFileRequest) {
        if (null == queryMediaFileRequest) {
            queryMediaFileRequest = new QueryMediaFileRequest();
        }
        MediaFile mediaFile = new MediaFile();
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getTag())) {
            mediaFile.setTag(queryMediaFileRequest.getTag());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getFileOriginalName())) {
            mediaFile.setFileOriginalName(queryMediaFileRequest.getFileOriginalName());
        }
        if (StringUtils.isNotEmpty(queryMediaFileRequest.getProcessStatus())) {
            mediaFile.setProcessStatus(queryMediaFileRequest.getProcessStatus());
        }
        // 条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("tag", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("fileOriginalName", ExampleMatcher.GenericPropertyMatchers.contains());
//                .withMatcher("processStatus", ExampleMatcher.GenericPropertyMatchers.exact())   默认精确匹配
        Example<MediaFile> example = Example.of(mediaFile, exampleMatcher);
        if (page <= 0) {
            page = 1;
        }
        page = page - 1;
        if (size <= 0) {
            size = 10;
        }
        Pageable pageable = PageRequest.of(page, size);
        Page<MediaFile> all = mediaFileRepository.findAll(example, pageable);
        long totalElements = all.getTotalElements();
        List<MediaFile> content = all.getContent();
        QueryResult<MediaFile> objectQueryResult = new QueryResult<>();
        objectQueryResult.setList(content);
        objectQueryResult.setTotal(totalElements);
        QueryResponseResult<Object> objectQueryResponseResult = new QueryResponseResult<>(CommonCode.SUCCESS, objectQueryResult);
        return objectQueryResponseResult;
    }
}
